package com.pzr.soccer.task.controller;

import com.pzr.soccer.common.consts.RedisConst;
import com.pzr.soccer.crawler.service.FootballCrawlerService;
import com.pzr.soccer.crawler.util.JvppeteerHelper;
import com.pzr.soccer.match.model.GameWrapper;
import com.pzr.soccer.task.domain.Task;
import com.pzr.soccer.task.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {
	//private Logger lg = LoggerFactory.getLogger("matchInfo controller");

	@Autowired
	TaskService taskService;

	@Autowired
	RedisTemplate<String,Object> redisTemplate;

	@Autowired
	MongoOperations operations;

	@Autowired
	FootballCrawlerService footballCrawlerService;

	@Autowired
	MongoOperations mongoOperations;

	@PostMapping("/addTask")
	public Task addTask(@RequestBody Task task) {
		
		 return operations.save(task);
	}
	
	@GetMapping("/allTasks")
	public List<Task> getAllTasks(){
	
		return operations.findAll(Task.class);
	}
	
	@GetMapping("/delete/{id}")
	public void deleteTask(@PathVariable(value = "id")String id) {
		 operations.remove(Query.query(Criteria.where("id").is(id)), Task.class);
	}
	
	@GetMapping("/liveTask")
	public List<String> getLiveTasks(){
		
		return taskService.getLiveTasksIds();
	}

	@GetMapping("/stopTask/{taskId}")
	public String stopTask(@PathVariable(value = "taskId")String taskId) {

		try {
			taskService.stopTask(taskId);
			return "stop " + taskId + " successfully!";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return "stop " + taskId + " failed! " + e.getMessage();
		}
	}

	@GetMapping("/stopAll")
	public String stopAllTask() {

		try {
			taskService.stopAllTasks();
			return "stop all  successfully!";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return "stop all failed! " + e.getMessage();
		}
	}


		@GetMapping("/startTask/{taskId}")
	public String startTask(@PathVariable(value = "taskId") String taskId) throws Exception {
		Task task = operations.findOne(Query.query(Criteria.where("id").is(taskId)), Task.class);
		Runnable runnable = null;
		if (task == null) {
			throw new Exception("no such task!");
		}
		try {
			switch (taskId) {
				case "scanTodayGame" -> {
					runnable = () -> {
						footballCrawlerService.scanToday();
					};
					taskService.startATask(runnable, task);
				}
				case "scanYesterday" -> {
					scanYesterday();//先运行一次
					runnable = this::scanYesterday;
					taskService.startATask(runnable, task);
				}
				default -> {
					System.out.println("this task is not activated!");
					throw new Exception("this task is not activated!");
				}
			}
		} catch (Exception e) {
			throw new Exception(e);
		}

		return taskId + "task is activeted  successfully !";
	}


	private void scanYesterday(){

		Set<String> urls = footballCrawlerService.gameListPageAddress(1);
		for(String url:urls){
			Element body= Jsoup.parse(JvppeteerHelper.getContent(url));
			Set<GameWrapper> gameWrappers = footballCrawlerService.scanHistory(body, LocalDate.now().minusDays(1));
			gameWrappers.forEach(gw->mongoOperations.save(gw.getGame()));
		}
	}

}
